<template>
  <el-card class="box-card">
    <template #header>
      <h2>歌曲评论管理</h2>
      <div class="card-header">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-input placeholder="请输入歌曲名" v-model="queryStr"></el-input>
          </el-col>
          <el-col :span="24">
            <el-input placeholder="请输入用户名" v-model="queryStrname"></el-input>
          </el-col>
          <el-col :span="24"> <!--下拉选择框-->
            <el-select v-model="queryStatus" placeholder="请选择状态">
              <el-option label="所有" value="all"></el-option>
              <el-option label="正常" value="正常"></el-option>
              <el-option label="被举报" value="被举报"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <div>
          <el-button class="button"  type="success" round @click="queryInfo">查询</el-button>
          <el-button type="danger"  round @click="multiDelete">多选删除</el-button>
        </div>
      </div>
    </template>
    <div>
      <!--表格形式输出数据-->
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" stripe highlight-current-row border>
        <el-table-column type="selection" width="55" fixed align="center"></el-table-column>
        <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
        <el-table-column prop="music_name" label="歌曲" width="200" align="center"></el-table-column>
        <el-table-column prop="user_name" label="评论用户" width="200" align="center"></el-table-column>
        <el-table-column prop="create_time" label="发布时间" width="250" align="center" :formatter="formatDate"></el-table-column>
        <el-table-column prop="status" label="评论状态" width="200" align="center"></el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="primary" plain round @click="openDetailDialog(scope.row.music_comment_id)">详情</el-button>
            <el-button type="warning" plain round @click="handleDelete(scope.row.music_comment_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 4, 5, 10]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </el-card>

  <!--详情框-->
  <el-dialog v-model="dialogDetailVisible" title="歌曲评论详情信息">
   <el-form :model="form">
     <el-form-item label="歌曲" :label-width="formLabelWidth">
      <el-form-item :label="form.music_name"></el-form-item>
     </el-form-item>
     <el-form-item label="评论用户" :label-width="formLabelWidth">
      <el-form-item :label="form.user_name"></el-form-item>
     </el-form-item>

     <el-form-item label="评论内容" :label-width="formLabelWidth">
      <div class="text" v-html="form.content" ></div>
     </el-form-item>

     <el-form-item label="发布时间" :label-width="formLabelWidth">
      <el-form-item :label="form.create_time" ></el-form-item>
     </el-form-item>
     <el-form-item label="评论状态" :label-width="formLabelWidth">
      <el-form-item :label="form.status"></el-form-item>
     </el-form-item>



   </el-form>
   <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDetailDialog">取消</el-button>
      </span>
 
   </template>
</el-dialog>


</template>



<script>
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  data() {
    return {
      dialogDetailVisible:false,  //详情对话框
      dialogFormVisible:false,  //对话框是否显示
      queryStr: "",  //歌曲名查询
      queryStrname: "",  //用户名查询
      queryStatus: "",   //状态查询
      multipleSelection: [],  //多选
      tableData: [],    //（分页请求数据）tableData 用于存储当前页面应该显示的表格数据。这些数据通常是从后端 API 获取的分页数据，它们会被直接渲染到 <el-table> 组件中。
      queryData: [],    //(执行查询过滤数据）queryData 用于存储所有从后端获取的评论数据，通常是在组件加载时获取的完整数据集，不仅限于当前页。
      pageInfo: {}, // 分页信息对象
      pageSize: 3, // 当前页条数
      currentPage: 1, // 当前页号
      form:{
        music_name: '',
        user_name: '',
        content: '',
        create_time: '',
        status: '',
        like_count: 0,
        comment_count: 0,
       },       //对话框表单 
      formLabelWidth:"140px",   //对话框label宽度
        title:"",                 //对话框标题
        btnName:"",                //对话框按钮文字
     
      }
   
    },
  methods: {
    //格式化日期
    formatDate(row, column, cellValue) {
      if (!cellValue) return "";
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    //复选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },

    ////选择每一页显示的记录数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getPageData(this.currentPage, this.pageSize);
      console.log("size:", pageSize);
    },

    //切换页号时得到当时页号
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum;
      this.getPageData(this.currentPage, this.pageSize);
      console.log("num:", pageNum);
    },

    // 获取分页数据
    //num和size：请求的页码和每页显示的条目数。
    getPageData(num, size) {
      this.$http.get("/v1/MusicCommentinfo", {
        params: { pageNum: num, pageSize: size }
      }).then((response) => {
        this.pageInfo = response.data;
        this.tableData = this.pageInfo.list;
        this.queryData = this.pageInfo.list; // 更新 queryData，使其包含当前页的数据列表。
        console.log(this.tableData);
      });
    },
    closeDetailDialog(){
      this.dialogDetailVisible = false  //对话框是否显示
      console.log("closeDetailDialog()...");
     },
      //详情对话框
      openDetailDialog(music_comment_id) {
      var _this = this;
      this.$http.get("/v1/MusicCommentinfo/"+music_comment_id).then(response => {
        _this.form = response.data; // 将后端返回的数据赋值给 form 对象
       // 格式化发布日期
       if (_this.form.create_time) {
            const date = new Date(_this.form.create_time);
            _this.form.create_time = date.toISOString().split('T')[0]; // 转换为 YYYY-MM-DD 格式
        }
      })
      this.dialogDetailVisible = true
    },

   

    // 删除单条评论
    handleDelete(music_comment_id) {
      ElMessageBox.confirm(
        '您确定要删除本条数据吗?',
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$http.delete("/v1/MusicComment/" + music_comment_id).then((response) => {
          console.log(response.data);
          if (response.data == 1) {
            ElMessage({
              type: 'success',
              message: '删除成功！',
            });
            this.getPageData(this.currentPage, this.pageSize); // 重新加载数据
          } else {
            ElMessage({
              type: 'warning',
              message: '删除失败！',
            });
          }
        });
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        });
      });
      console.log("singleDelete()...");
    },

    //多选删除
    multiDelete() {
      console.log("multiDelete()...");
      ElMessageBox.confirm(
        '您确定要删除当前选中的多条数据吗?',
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        var num = 0;
        this.multipleSelection.forEach(item => {
          var music_comment_id = item.music_comment_id;
          this.$http.delete("/v1/MusicComment/" + music_comment_id).then((response) => {
            console.log(response.data);
            if (response.data == 1) {
              num = num + 1;
              ElMessage({
                type: 'success',
                message: '你成功删除' + num + '条记录！',
              });
            }
          });
        });
        this.getPageData(this.currentPage, this.pageSize); // 重新加载数据
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        });
      });
    },

    //实现多个查询
    queryInfo() {
      this.currentPage = 1;  //每次执行查询，从第一页开始显示结果
      console.log("查询信息：", this.queryStr, this.queryStrname, this.queryStatus);

      // 过滤逻辑：检查是否有数据输入,并且设置查询状态默认为“所有”，filter方法筛选数据
      if (this.queryStr.trim().length > 0 || this.queryStrname.trim().length > 0 || this.queryStatus !== "all") {
        this.tableData = this.queryData.filter(item => {
          const matchesMusicName = (this.queryStr.trim().length === 0 || item.music_name.includes(this.queryStr.trim()));//用于检查一个字符串（item.title）数据库中存储的，是否包含另一个字符串（this.queryStr）输入的
          const matchesUserName = (this.queryStrname.trim().length === 0 || item.user_name.includes(this.queryStrname.trim()));
          const matchesStatus = (this.queryStatus === "" || item.status === this.queryStatus);
          return matchesMusicName && matchesUserName && matchesStatus;
        });
      } else {
        this.tableData = this.queryData; // 当查询条件为空时，显示所有数据
      }
      console.log("Filtered Table Data:", this.tableData);
    }
  },
  mounted() {
    this.getPageData(1, 10);
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center; /* 垂直居中 */
}
.el-row {
  width: 70%; /* 确保行占满整行 */
}
.el-col {
  flex: 1; /* 让列填充可用空间 */
}
.buttons {  
  display: flex;  
  justify-content: flex-start;  
  gap: 10px; /* 按钮间的距离 */  
}
.text {
  width: 700px; /* 使内容宽度充满父容器 */
  height: 50px; /* 设置一个固定的高度，根据需要调整 */
  overflow-y: auto; /* 当内容超出高度时启用垂直滚动条 */
  word-break: break-word; /* 允许长单词在达到容器边界时换行 */
  white-space: normal; /* 允许空白处换行 */
  line-height: 1.5; /* 根据字体大小调整行高，以控制每行字数 */
}
</style>
